package com.ruoyi.api.controller;

import com.ruoyi.api.service.ApprovalService;
import com.ruoyi.api.service.VehicleService;
import com.ruoyi.api.vo.Approval;
import com.ruoyi.api.vo.Vehicle;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.tio.TioWsMsgHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 车辆租用管理
 */
@RestController
@RequestMapping("/api/sys/approval")
public class ApprovalController {

    @Autowired
    private ApprovalService approvalService;

    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SseController sseController;

    /**
     * 添加车辆租用申请
     * @param approval
     * @return
     */
    @PostMapping("add")
    public AjaxResult addApproval(@RequestBody Approval approval) throws IOException {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        approval.setNickName(user.getNickName());
        approval.setUserId(user.getUserId());
        approval.setState(1);
        approval.setPersonnel(0);
        approval.setEffective(1);
        //判断是否是管理员,是管理员的话属于分配人员以及对应车辆
        if(user.getUserId() == 1){
            approval.setPersonnel(1);
        }
        //判断该车辆是否已经被租用(车辆预约时间和申请通过时间不能有交集)
        List<Approval> list = approvalService.selectByCarInfo(approval);
        //判断该车辆是否在申请中或使用中,在未使用状态可以进行申请
        if(list.isEmpty()){
            //添加车辆租用
            boolean a = approvalService.addApproval(approval);
            //判断是否是管理员,是管理员的话属于分配人员以及对应车辆
            if(user.getUserId() == 1){
                approvalService.updateById(approval.getId(),2);
            }
            if(a) {
//                //添加成功后修改车辆信息,使其变为使用中
//                vehicleService.update(approval.getCarInfo(), 0);// 推送预约信息给固定管理员
                // 推送预约信息给管理员
//                SysUser sysUser = SecurityUtils.getLoginUser().getUser();
                sseController.sendSSEMessage("1","您有一个新的消息请查收");
                return AjaxResult.success("上传成功");
            }
        }else if(!list.isEmpty()){
            return AjaxResult.error("车辆已经被使用,请申请其他车辆");
        }
        return AjaxResult.error("上传失败");
    }

    /**
     * 根据用户id查询
     * @param userId
     * @return
     */
    @GetMapping("select/{userId}")
    public AjaxResult selectApproval(@PathVariable Long userId){
        List<Approval> list = approvalService.selectApproval(userId);
        return AjaxResult.success(list);
    }

    /**
     * 根据id修改
     * @param approval
     * @return
     */
    @PutMapping("update")
    public AjaxResult updateApproval(@RequestBody Approval approval){
        approvalService.updateApproval(approval);
        return AjaxResult.success();
    }

    /**
     * 查询所有预约信息
     * @return
     */
    @GetMapping("selectAll")
    public AjaxResult selectAll(){
        Date date = new Date();
        List<Approval> list = approvalService.selectAll();
        if(list.isEmpty()){
            return AjaxResult.error("没有查到待审核数据");
        }
        for (Approval approval : list) {
            //判断结束时间与现在时间对比,结束时间小于当前时间时失效这条申请,并从list中删除,将车辆状态变为可预约
            long timestamp = date.getTime();
            redisCache.setCacheObject("carInfo:" + approval.getCarInfo(),0);
            if(timestamp > approval.getEndTime()){
                approvalService.updateByIdEff(approval.getId());
                list.remove(approval);
            }
            //当前时间在对象开始时间和结束时间之间的话并且车辆状态为通过审批,修改该车辆状态为使用中
            if(timestamp >= approval.getBeginTime() && timestamp <= approval.getEndTime() && approval.getState() == 2) {
                vehicleService.update(approval.getCarInfo(), 1);
                redisCache.setCacheObject("carInfo:" + approval.getCarInfo(),1);
            }
        }
        for (Approval approval : list) {
            int a = redisCache.getCacheObject("carInfo:" + approval.getCarInfo());
            //当a=0时说明该车辆在当前时间没有审批使用,所以将其状态修改为0
            if(a == 0){
                vehicleService.update(approval.getCarInfo(),0);
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 删除
     */
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestBody Map<String,List<Long>> ids){
        if(ids != null) {
            List<Long> id = ids.get("id");
            if (id != null) {
                boolean a = approvalService.deleteById(id);
                if(a){
                    return AjaxResult.success("删除成功");
                }
            }
        }
        return AjaxResult.error("删除失败");
    }
        /**
         * 根据id进行修改
         * @param id
         * @param state
         * @return
         */
        @GetMapping("/updateById")
        public AjaxResult updateById(@RequestParam Long id,
                                     @RequestParam Integer state
                                    )  {
            if(state == 0){
                //修改人员预约的状态,没有通过审批,直接做失效处理
//                approvalService.updateById(id,0);
                approvalService.updateByIdEff(id);
                return AjaxResult.success("申请失败");
            }else if(state == 2){
                //当管理员通过该申请时,修改状态值为2
                approvalService.updateById(id,2);
            }
            return AjaxResult.success("修改成功");
        }

    /**
     * 查询某个车辆使用情况(已使用)
      * @param carId
     * @return
     */
    @PostMapping("selectCar")
    public AjaxResult selectCare(@RequestParam String carId){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<Approval> list = approvalService.selectByCar(carId,user.getUserId());
        return AjaxResult.success(list);
    }

    /**
     * 根据userId查询车辆信息
     * @param userId
     * @return
     */
    @PostMapping("byUserIdGetCar")
    public AjaxResult selectCar(@RequestParam("userId") String userId){
        List<Vehicle> list1 = new ArrayList<>();
        //如果是管理员,返回所有预约成功且已经使用过的车辆信息
        if(userId.equals("1")){
            Set<String> set = approvalService.selectByUserIds();
            if (!set.isEmpty()) {
                for (String s : set) {
                    Vehicle vehicle = vehicleService.selectByCarId(s);
                    list1.add(vehicle);
                }
            }
        }else {
            List<String> list = approvalService.selectByUserId(userId);
            if (!list.isEmpty()) {
                for (String s : list) {
                    Vehicle vehicle = vehicleService.selectByCarId(s);
                    list1.add(vehicle);
                }
            }
        }
        return AjaxResult.success(list1);
    }
}

